package com.slw.emergency.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.slw.emergency.constant.InitConstant;
import com.slw.emergency.entity.Epidemic;
import com.slw.emergency.entity.OverseaEpidemic;
import com.slw.emergency.enums.StatusEnum;
import org.springframework.util.StringUtils;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

public class JsonUtil {
    /**
     * 将接口数据转换为中国疫情数据Epidemic实体类(2月18版本)
     */
    public static List<Epidemic> jsonResolveChina(String str){
        if (StringUtils.isEmpty(str)){
            return null;
        }
        List<Epidemic> epidemicList = new ArrayList<>();  //中国疫情数据

        //数据获取时间
        String getTime = JSONObject.parseObject(str).getString("timestamp");

        JSONObject jsonObject = JSONObject.parseObject(str).getJSONObject("data");
        JSONObject china = jsonObject.getJSONArray("areaTree").getJSONObject(0);
        JSONArray provinces = china.getJSONArray("children");
        //遍历每个省
        for (int i = 0; i < provinces.size(); i++){
            JSONObject province = provinces.getJSONObject(i);
            String provinceName = province.getString("name");
            String provinceCode = province.getString("id"); //编号
            JSONArray cities = province.getJSONArray("children");
            if(isSpecial(provinceCode) || null == cities || cities.size() == 0 ){    //如果是直辖市或特别行政区,或没有地市数据
                Epidemic epidemic = getEpidemic(getTime, provinceName, province);
                epidemic.setCity(provinceName);
                epidemic.setLng(getLng(provinceName)[0]);
                epidemic.setLat(getLng(provinceName)[1]);
                epidemicList.add(epidemic);
            }else {
                //遍历每个市
                for (int j = 0; j < cities.size(); j++){
                    JSONObject city = cities.getJSONObject(j);
                    String cityName = city.getString("name");
                    String cityCode = city.getString("id");
                    Epidemic epidemic = getEpidemic(getTime, provinceName, city);
                    epidemic.setCity(cityName);
                    epidemic.setLng(getLng(cityName)[0]);
                    epidemic.setLat(getLng(cityName)[1]);
                    epidemicList.add(epidemic);
                }
            }
        }
        return epidemicList;
    }

    //将接口数据转换为海外疫情数据
    public static List<OverseaEpidemic> jsonResolveOver(String str){
        if (StringUtils.isEmpty(str)){
            return null;
        }
        List<OverseaEpidemic> overseaEpidemics = new ArrayList<>();  //海外疫情数据

        //数据获取时间
        String getTime = JSONObject.parseObject(str).getString("timestamp");

        JSONObject jsonObject = JSONObject.parseObject(str).getJSONObject("data");
        JSONArray countries = jsonObject.getJSONArray("areaTree");
        for(int i=1; i<countries.size();i++){   //从第2项开始, 获取海外数据
            JSONObject country = countries.getJSONObject(i);
            OverseaEpidemic overseaEpidemic = new OverseaEpidemic();
            //设置每日总数
            overseaEpidemic.setCountry(country.getString("name"));
            JSONObject total = country.getJSONObject("total");
            overseaEpidemic.setCntSumConfirmed(StringUtils.isEmpty(total.getString("confirm"))?"0": total.getString("confirm"));
            overseaEpidemic.setCntSumCured(StringUtils.isEmpty(total.getString("heal"))?"0": total.getString("heal"));
            overseaEpidemic.setCntSumDead(StringUtils.isEmpty(total.getString("dead"))?"0": total.getString("dead"));
            overseaEpidemic.setCntSumSuspected(StringUtils.isEmpty(total.getString("suspect"))?"0": total.getString("suspect"));
            //设置每日新增
            JSONObject today = country.getJSONObject("today");
            overseaEpidemic.setCntConfirm(StringUtils.isEmpty(today.getString("confirm"))?"0": today.getString("confirm"));
            overseaEpidemic.setCntHeal(StringUtils.isEmpty(today.getString("heal"))?"0": today.getString("heal"));
            overseaEpidemic.setCntDead(StringUtils.isEmpty(today.getString("dead"))?"0": today.getString("dead"));
            overseaEpidemic.setCntSuspect(StringUtils.isEmpty(today.getString("suspect"))?"0": today.getString("suspect"));

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            try {
                Long timeLong = Long.parseLong(getTime);
                overseaEpidemic.setCreateTime(sdf.parse(sdf.format(timeLong)));
            } catch (ParseException e) {
                e.printStackTrace();
            }
            overseaEpidemic.setIsLatest(StatusEnum.YES.getStutus());
            overseaEpidemics.add(overseaEpidemic);
        }


        return overseaEpidemics;
    }

    private static Epidemic getEpidemic(String date, String provinceName, JSONObject json){
        Epidemic epidemic = new Epidemic();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        //设置每日总数
        JSONObject total = json.getJSONObject("total");
        epidemic.setCntSumConfirmed(StringUtils.isEmpty(total.getString("confirm"))?"0": total.getString("confirm"));
        epidemic.setCntSumCured(StringUtils.isEmpty(total.getString("heal"))?"0": total.getString("heal"));
        epidemic.setCntSumDead(StringUtils.isEmpty(total.getString("dead"))?"0": total.getString("dead"));
        epidemic.setCntSumSuspected(StringUtils.isEmpty(total.getString("suspect"))?"0": total.getString("suspect"));
        //设置每日新增
        JSONObject today = json.getJSONObject("today");
        epidemic.setCntConfirm(StringUtils.isEmpty(today.getString("confirm"))?"0": today.getString("confirm"));
        epidemic.setCntHeal(StringUtils.isEmpty(today.getString("heal"))?"0": today.getString("heal"));
        epidemic.setCntDead(StringUtils.isEmpty(today.getString("dead"))?"0": today.getString("dead"));
        epidemic.setCntSuspect(StringUtils.isEmpty(today.getString("suspect"))?"0": today.getString("suspect"));

        epidemic.setProvince(provinceName);
        try {
            Long timeLong = Long.parseLong(date);
            epidemic.setCreateTime(sdf.parse(sdf.format(timeLong)));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        epidemic.setIsLatest(StatusEnum.YES.getStutus());
        return epidemic;
    }

    //根据城市名获取经纬度
    public static String[] getLng(String city){
        Map<String, JSONObject> map = InitConstant.lngMap;
        for(Map.Entry<String, JSONObject> entry : InitConstant.lngMap.entrySet()){
            JSONObject cityItem = entry.getValue();
            if(cityItem.getString("name").startsWith(city)){
                return  cityItem.getString("center").split(",");
            }
        }
        return new String[2];
    }

    //根据code获取经纬度
    public static String[] getLngByCode(String code){
        Map<String, JSONObject> map = InitConstant.lngMap;
        try {
            JSONObject item = map.get(code);
            return item.getString("center").split(",");
        }catch (Exception e){
            return new String[2];
        }
    }

    //判断是否是直辖市和特别行政区
    public static boolean isSpecial(String code){
        StringBuffer sb = new StringBuffer();
        sb.append("110000");
        sb.append("120000");
        sb.append("310000");
        sb.append("500000");
        sb.append("810000");
        sb.append("820000");
        if (sb.indexOf(code) !=-1){
            return true;
        }
        return false;
    }

    //将接口数据转换为Epidemic实体类(2月17版本)
//    public static List<Epidemic> jsonResolve(String rawJson){
//        List<Epidemic> EpidemicList = new ArrayList<>();
//        JSONObject jsonObject = JSON.parseObject(rawJson);
//        JSONArray days = jsonObject.getJSONArray("resultValue");
//        days.forEach(dayItem -> {
//            JSONObject day = (JSONObject) dayItem;
//            String date = day.getString("date");
//            JSONArray provinces = day.getJSONArray("values");
//            provinces.forEach(provinceItem -> {
//                JSONObject province = (JSONObject) provinceItem;
//                String provinceName = province.getString("provinceName");
//                JSONArray cities = province.getJSONArray("cities");
//                if(null != cities && cities.size() > 0) {
//                    cities.forEach(cityItem -> {
//                        JSONObject city = (JSONObject) cityItem;
//                        Epidemic epidemic = getEpidemic(date, provinceName, city);
//                        EpidemicList.add(epidemic);
//                    });
//                }else{
//                    Epidemic epidemic = getEpidemic(date, provinceName, province);
////                    epidemic.setLng(InitConstant.lngMap.get(provinceName)[0]);
////                    epidemic.setLat(InitConstant.lngMap.get(provinceName)[1]);
//                    EpidemicList.add(epidemic);
//                }
//            });
//        });
//        return EpidemicList;
//    }
//
//    //2月17版本
//    private static Epidemic getEpidemic(String date, String provinceName, JSONObject json){
//        Epidemic epidemic = new Epidemic();
//        epidemic.setProvince(provinceName);
//        epidemic.setCntSumConfirmed(json.getString("confirmed"));
//        epidemic.setCntSumCured(json.getString("Cured"));
//        epidemic.setCntSumSuspected(json.getString("suspected"));
//        epidemic.setCntSumDead(json.getString("dead"));
//        String cityName = json.getString("cityName");
//        if (StringUtils.isEmpty(cityName)){
//            cityName = provinceName;
//        }
//        epidemic.setCity(cityName);
////        epidemic.setLng(getLng(cityName)[0]);
////        epidemic.setLat(getLng(cityName)[1]);
//        epidemic.setIsLatest(StatusEnum.YES.getStutus());
//        try{
//            SimpleDateFormat df = new SimpleDateFormat("yyyy.MM.dd");
//            epidemic.setCreateTime(df.parse(date));
//        }catch (Exception e){
//            e.printStackTrace();
//        }
//        return epidemic;
//    }

    //根据城市名获取经纬度（2月17版本）
//    public static String[] getLng(String city){
//        for(Map.Entry<String, String> entry : InitConstant.lngMap.entrySet()){
//            String mapKey = entry.getKey();
//            if (mapKey.indexOf(city)!=-1){
//                return  entry.getValue().getString("center").split(",");
//            }
//        }
//        return new String[2];
//    }
}
